
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>TemplateResponse 和 SimpleTemplateResponse &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="next" title="Unicode 数据" href="unicode.html" />
    <link rel="prev" title="Django 模板语言：对于 Python 开发者" href="templates/api.html" />



 
<script src="../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="templates/api.html" title="Django 模板语言：对于 Python 开发者">previous</a>
     |
    <a href="index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="unicode.html" title="Unicode 数据">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-template-response">
            
  <div class="section" id="s-module-django.template.response">
<span id="s-templateresponse-and-simpletemplateresponse"></span><span id="module-django.template.response"></span><span id="templateresponse-and-simpletemplateresponse"></span><h1><code class="docutils literal notranslate"><span class="pre">TemplateResponse</span></code> 和 <code class="docutils literal notranslate"><span class="pre">SimpleTemplateResponse</span></code><a class="headerlink" href="#module-django.template.response" title="永久链接至标题">¶</a></h1>
<p>标准 <a class="reference internal" href="request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponse</span></code></a> 对象是静态结构。它们在构建时提供了一个预渲染的内容块，虽然这些内容可以修改，但它的形式并不便于进行修改。</p>
<p>然而，有时允许装饰者或中间件在视图构建响应后修改响应可能是有益的。例如，你可能想改变所使用的模板，或者在上下文中放入额外的数据。</p>
<p>TemplateResponse 提供了一种方法来实现这一点。与基本的 <a class="reference internal" href="request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponse</span></code></a> 对象不同，TemplateResponse 对象保留了模板和上下文的细节，这些细节是由视图提供的，用于计算响应。响应的最终输出直到需要时才会计算，在响应过程的后面。</p>
<div class="section" id="s-simpletemplateresponse-objects">
<span id="simpletemplateresponse-objects"></span><h2><code class="docutils literal notranslate"><span class="pre">SimpleTemplateResponse</span></code> 对象<a class="headerlink" href="#simpletemplateresponse-objects" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="django.template.response.SimpleTemplateResponse">
<em class="property">class </em><code class="descname">SimpleTemplateResponse</code><a class="headerlink" href="#django.template.response.SimpleTemplateResponse" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<div class="section" id="s-attributes">
<span id="attributes"></span><h3>属性<a class="headerlink" href="#attributes" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.template.response.SimpleTemplateResponse.template_name">
<code class="descclassname">SimpleTemplateResponse.</code><code class="descname">template_name</code><a class="headerlink" href="#django.template.response.SimpleTemplateResponse.template_name" title="永久链接至目标">¶</a></dt>
<dd><p>要渲染的模板的名称。接受一个依赖于后台的模板对象（如 <a class="reference internal" href="../topics/templates.html#django.template.loader.get_template" title="django.template.loader.get_template"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_template()</span></code></a> 返回的模板对象）、一个模板的名称或一个模板名称列表。</p>
<p>例如： <code class="docutils literal notranslate"><span class="pre">['foo.html',</span> <span class="pre">'path/to/bar.html']</span></code></p>
</dd></dl>

<dl class="attribute">
<dt id="django.template.response.SimpleTemplateResponse.context_data">
<code class="descclassname">SimpleTemplateResponse.</code><code class="descname">context_data</code><a class="headerlink" href="#django.template.response.SimpleTemplateResponse.context_data" title="永久链接至目标">¶</a></dt>
<dd><p>渲染模板时要使用的上下文数据，必须是 <a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#dict" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>。</p>
<p>例如： <code class="docutils literal notranslate"><span class="pre">{'foo':</span> <span class="pre">123}</span></code></p>
</dd></dl>

<dl class="attribute">
<dt id="django.template.response.SimpleTemplateResponse.rendered_content">
<code class="descclassname">SimpleTemplateResponse.</code><code class="descname">rendered_content</code><a class="headerlink" href="#django.template.response.SimpleTemplateResponse.rendered_content" title="永久链接至目标">¶</a></dt>
<dd><p>响应内容的当前渲染值，使用当前模板和上下文数据。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.template.response.SimpleTemplateResponse.is_rendered">
<code class="descclassname">SimpleTemplateResponse.</code><code class="descname">is_rendered</code><a class="headerlink" href="#django.template.response.SimpleTemplateResponse.is_rendered" title="永久链接至目标">¶</a></dt>
<dd><p>表示响应内容是否已呈现的布尔值。</p>
</dd></dl>

</div>
<div class="section" id="s-methods">
<span id="methods"></span><h3>方法<a class="headerlink" href="#methods" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="django.template.response.SimpleTemplateResponse.__init__">
<code class="descclassname">SimpleTemplateResponse.</code><code class="descname">__init__</code>(<em>template</em>, <em>context=None</em>, <em>content_type=None</em>, <em>status=None</em>, <em>charset=None</em>, <em>using=None</em>, <em>headers=None</em>)<a class="headerlink" href="#django.template.response.SimpleTemplateResponse.__init__" title="永久链接至目标">¶</a></dt>
<dd><p>用给定的模板、上下文、内容类型、HTTP 状态和字符集实例化一个 <a class="reference internal" href="#django.template.response.SimpleTemplateResponse" title="django.template.response.SimpleTemplateResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleTemplateResponse</span></code></a> 对象。</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">template</span></code></dt>
<dd>依赖于后台的模板对象（如 <a class="reference internal" href="../topics/templates.html#django.template.loader.get_template" title="django.template.loader.get_template"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_template()</span></code></a> 返回的模板对象），模板的名称，或者模板名称的列表。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">context</span></code></dt>
<dd>一个 <a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#dict" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 的值，用于添加到模板上下文中。默认情况下，这是一个空字典。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">content_type</span></code></dt>
<dd>包含在 HTTP <code class="docutils literal notranslate"><span class="pre">Content-Type</span></code> 头中的值，包括 MIME 类型规格和字符集编码。如果指定了 <code class="docutils literal notranslate"><span class="pre">content_type</span></code>，则使用其值。否则，使用 <code class="docutils literal notranslate"><span class="pre">'text/html'</span></code>。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">status</span></code></dt>
<dd>响应的 HTTP 状态码。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">charset</span></code></dt>
<dd>响应将被编码的字符集。如果没有给定，将从 <code class="docutils literal notranslate"><span class="pre">content_type</span></code> 中提取，如果不成功，将使用 <a class="reference internal" href="settings.html#std:setting-DEFAULT_CHARSET"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DEFAULT_CHARSET</span></code></a> 设置。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">using</span></code></dt>
<dd>用于加载模板的模板引擎的 <a class="reference internal" href="settings.html#std:setting-TEMPLATES-NAME"><code class="xref std std-setting docutils literal notranslate"><span class="pre">NAME</span></code></a> 。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">headers</span></code></dt>
<dd>A <a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#dict" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> of HTTP headers to add to the response.</dd>
</dl>
<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p>The <code class="docutils literal notranslate"><span class="pre">headers</span></code> parameter was added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="django.template.response.SimpleTemplateResponse.resolve_context">
<code class="descclassname">SimpleTemplateResponse.</code><code class="descname">resolve_context</code>(<em>context</em>)<a class="headerlink" href="#django.template.response.SimpleTemplateResponse.resolve_context" title="永久链接至目标">¶</a></dt>
<dd><p>预处理将用于渲染模板的上下文数据。接受一个 <a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#dict" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 的上下文数据。默认情况下，返回相同的 <a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#dict" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>。</p>
<p>覆盖此方法，以自定义上下文。</p>
</dd></dl>

<dl class="method">
<dt id="django.template.response.SimpleTemplateResponse.resolve_template">
<code class="descclassname">SimpleTemplateResponse.</code><code class="descname">resolve_template</code>(<em>template</em>)<a class="headerlink" href="#django.template.response.SimpleTemplateResponse.resolve_template" title="永久链接至目标">¶</a></dt>
<dd><p>解析用于渲染的模板实例。接受一个依赖于后台的模板对象（例如 <a class="reference internal" href="../topics/templates.html#django.template.loader.get_template" title="django.template.loader.get_template"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_template()</span></code></a> 返回的对象），模板的名称，或者模板名称的列表。</p>
<p>返回要渲染的依赖于后台的模板对象实例。</p>
<p>覆盖此方法，以便自定义模板加载。</p>
</dd></dl>

<dl class="method">
<dt id="django.template.response.SimpleTemplateResponse.add_post_render_callback">
<code class="descclassname">SimpleTemplateResponse.</code><code class="descname">add_post_render_callback</code>()<a class="headerlink" href="#django.template.response.SimpleTemplateResponse.add_post_render_callback" title="永久链接至目标">¶</a></dt>
<dd><p>添加一个回调，将在渲染发生后被调用。该钩子可用于将某些处理操作（如缓存）推迟到渲染发生后。</p>
<p>如果 <a class="reference internal" href="#django.template.response.SimpleTemplateResponse" title="django.template.response.SimpleTemplateResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleTemplateResponse</span></code></a> 已经被渲染，回调将被立即调用。</p>
<p>当调用时，回调将被传递一个单一的参数——渲染的 <a class="reference internal" href="#django.template.response.SimpleTemplateResponse" title="django.template.response.SimpleTemplateResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleTemplateResponse</span></code></a> 实例。</p>
<p>如果回调返回一个不是 <code class="docutils literal notranslate"><span class="pre">None</span></code> 的值，这个值将被用作响应，而不是原来的响应对象（并将传递给下一个渲染后回调等）。</p>
</dd></dl>

<dl class="method">
<dt id="django.template.response.SimpleTemplateResponse.render">
<code class="descclassname">SimpleTemplateResponse.</code><code class="descname">render</code>()<a class="headerlink" href="#django.template.response.SimpleTemplateResponse.render" title="永久链接至目标">¶</a></dt>
<dd><p>将 <code class="docutils literal notranslate"><span class="pre">response.content</span></code> 设置为由 <a class="reference internal" href="#django.template.response.SimpleTemplateResponse.rendered_content" title="django.template.response.SimpleTemplateResponse.rendered_content"><code class="xref py py-attr docutils literal notranslate"><span class="pre">SimpleTemplateResponse.rendered_content</span></code></a> 得到的结果，运行所有的渲染后回调，并返回结果的响应对象。</p>
<p><code class="docutils literal notranslate"><span class="pre">render()</span></code> 只有在第一次被调用时才会产生效果。在以后的调用中，它将返回第一次调用的结果。</p>
</dd></dl>

</div>
</div>
<div class="section" id="s-templateresponse-objects">
<span id="templateresponse-objects"></span><h2><code class="docutils literal notranslate"><span class="pre">TemplateResponse</span></code> 对象<a class="headerlink" href="#templateresponse-objects" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="django.template.response.TemplateResponse">
<em class="property">class </em><code class="descname">TemplateResponse</code><a class="headerlink" href="#django.template.response.TemplateResponse" title="永久链接至目标">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">TemplateResponse</span></code> 是 <a class="reference internal" href="#django.template.response.SimpleTemplateResponse" title="django.template.response.SimpleTemplateResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleTemplateResponse</span></code></a> 的一个子类，它知道当前的 <a class="reference internal" href="request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpRequest</span></code></a>。</p>
</dd></dl>

<div class="section" id="s-id1">
<span id="id1"></span><h3>方法<a class="headerlink" href="#id1" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="django.template.response.TemplateResponse.__init__">
<code class="descclassname">TemplateResponse.</code><code class="descname">__init__</code>(<em>request</em>, <em>template</em>, <em>context=None</em>, <em>content_type=None</em>, <em>status=None</em>, <em>charset=None</em>, <em>using=None</em>, <em>headers=None</em>)<a class="headerlink" href="#django.template.response.TemplateResponse.__init__" title="永久链接至目标">¶</a></dt>
<dd><p>用给定的请求、模板、上下文、内容类型、HTTP 状态和字符集实例化一个 <a class="reference internal" href="#django.template.response.TemplateResponse" title="django.template.response.TemplateResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemplateResponse</span></code></a> 对象。</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">request</span></code></dt>
<dd>一个 <a class="reference internal" href="request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpRequest</span></code></a> 实例。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">template</span></code></dt>
<dd>依赖于后台的模板对象（如 <a class="reference internal" href="../topics/templates.html#django.template.loader.get_template" title="django.template.loader.get_template"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_template()</span></code></a> 返回的模板对象），模板的名称，或者模板名称的列表。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">context</span></code></dt>
<dd>一个 <a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#dict" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 的值，用于添加到模板上下文中。默认情况下，这是一个空字典。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">content_type</span></code></dt>
<dd>包含在 HTTP <code class="docutils literal notranslate"><span class="pre">Content-Type</span></code> 头中的值，包括 MIME 类型规格和字符集编码。如果指定了 <code class="docutils literal notranslate"><span class="pre">content_type</span></code>，则使用其值。否则，使用 <code class="docutils literal notranslate"><span class="pre">'text/html'</span></code>。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">status</span></code></dt>
<dd>响应的 HTTP 状态码。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">charset</span></code></dt>
<dd>响应将被编码的字符集。如果没有给定，将从 <code class="docutils literal notranslate"><span class="pre">content_type</span></code> 中提取，如果不成功，将使用 <a class="reference internal" href="settings.html#std:setting-DEFAULT_CHARSET"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DEFAULT_CHARSET</span></code></a> 设置。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">using</span></code></dt>
<dd>用于加载模板的模板引擎的 <a class="reference internal" href="settings.html#std:setting-TEMPLATES-NAME"><code class="xref std std-setting docutils literal notranslate"><span class="pre">NAME</span></code></a> 。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">headers</span></code></dt>
<dd>A <a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#dict" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> of HTTP headers to add to the response.</dd>
</dl>
<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p>The <code class="docutils literal notranslate"><span class="pre">headers</span></code> parameter was added.</p>
</div>
</dd></dl>

</div>
</div>
<div class="section" id="s-the-rendering-process">
<span id="the-rendering-process"></span><h2>渲染过程<a class="headerlink" href="#the-rendering-process" title="永久链接至标题">¶</a></h2>
<p>在将 <a class="reference internal" href="#django.template.response.TemplateResponse" title="django.template.response.TemplateResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemplateResponse</span></code></a> 实例返回给客户端之前，必须对其进行渲染。渲染过程将模板和上下文的中间表示方式，变成最终的字节流，可以提供给客户端。</p>
<p>在三种情况下，会出现 <code class="docutils literal notranslate"><span class="pre">TemplateResponse</span></code> 被渲染：</p>
<ul class="simple">
<li>当使用 <a class="reference internal" href="#django.template.response.SimpleTemplateResponse.render" title="django.template.response.SimpleTemplateResponse.render"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SimpleTemplateResponse.render()</span></code></a> 方法显式渲染 <code class="docutils literal notranslate"><span class="pre">TemplateResponse</span></code> 实例时。</li>
<li>当通过指定 <code class="docutils literal notranslate"><span class="pre">response.content</span></code> 明确设置响应的内容时。</li>
<li>通过模板响应中间件后，但在通过响应中间件之前。</li>
</ul>
<p>一个 <code class="docutils literal notranslate"><span class="pre">TemplateResponse</span></code> 只能被渲染一次。第一次调用 <a class="reference internal" href="#django.template.response.SimpleTemplateResponse.render" title="django.template.response.SimpleTemplateResponse.render"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SimpleTemplateResponse.render()</span></code></a> 时，会设置响应的内容；后续的渲染调用不会改变响应内容。</p>
<p>但是，当 <code class="docutils literal notranslate"><span class="pre">response.content</span></code> 被显式分配时，变化总是被应用。如果你想强制重新渲染内容，你可以重新执行渲染的内容，并手动分配响应的内容：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Set up a rendered TemplateResponse</span>
<span class="o">&gt;&gt;&gt;</span> <span class="kn">from</span> <span class="nn">django.template.response</span> <span class="kn">import</span> <span class="n">TemplateResponse</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">t</span> <span class="o">=</span> <span class="n">TemplateResponse</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;original.html&#39;</span><span class="p">,</span> <span class="p">{})</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">()</span>
<span class="o">&gt;&gt;&gt;</span> <span class="nb">print</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">content</span><span class="p">)</span>
<span class="n">Original</span> <span class="n">content</span>

<span class="c1"># Re-rendering doesn&#39;t change content</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">t</span><span class="o">.</span><span class="n">template_name</span> <span class="o">=</span> <span class="s1">&#39;new.html&#39;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">()</span>
<span class="o">&gt;&gt;&gt;</span> <span class="nb">print</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">content</span><span class="p">)</span>
<span class="n">Original</span> <span class="n">content</span>

<span class="c1"># Assigning content does change, no render() call required</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">t</span><span class="o">.</span><span class="n">content</span> <span class="o">=</span> <span class="n">t</span><span class="o">.</span><span class="n">rendered_content</span>
<span class="o">&gt;&gt;&gt;</span> <span class="nb">print</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">content</span><span class="p">)</span>
<span class="n">New</span> <span class="n">content</span>
</pre></div>
</div>
<div class="section" id="s-post-render-callbacks">
<span id="post-render-callbacks"></span><h3>渲染后回调<a class="headerlink" href="#post-render-callbacks" title="永久链接至标题">¶</a></h3>
<p>有些操作——例如缓存——不能在未渲染的模板上执行。它们必须在一个完全完整的、已渲染的响应上执行。</p>
<p>如果你使用的是中间件，你可以这样做。中间件提供了多种机会来处理从视图退出时的响应。如果你把行为放在响应中间件中，就会保证在模板渲染发生后执行。</p>
<p>然而，如果你使用的是一个装饰器，则不存在同样的机会。任何在装饰器中定义的行为都会被立即处理。</p>
<p>为了弥补这一点（以及任何其他类似的用例）， <a class="reference internal" href="#django.template.response.TemplateResponse" title="django.template.response.TemplateResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemplateResponse</span></code></a> 允许你注册回调，当渲染完成后，这些回调将被调用。使用这个回调，你可以将关键的处理推迟到可以保证渲染内容可用的时候。</p>
<p>要定义一个渲染后的回调，定义一个接受一个参数 response 的函数，然后用模板响应注册该函数：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.template.response</span> <span class="kn">import</span> <span class="n">TemplateResponse</span>

<span class="k">def</span> <span class="nf">my_render_callback</span><span class="p">(</span><span class="n">response</span><span class="p">):</span>
    <span class="c1"># Do content-sensitive processing</span>
    <span class="n">do_post_processing</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c1"># Create a response</span>
    <span class="n">response</span> <span class="o">=</span> <span class="n">TemplateResponse</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;mytemplate.html&#39;</span><span class="p">,</span> <span class="p">{})</span>
    <span class="c1"># Register the callback</span>
    <span class="n">response</span><span class="o">.</span><span class="n">add_post_render_callback</span><span class="p">(</span><span class="n">my_render_callback</span><span class="p">)</span>
    <span class="c1"># Return the response</span>
    <span class="k">return</span> <span class="n">response</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">my_render_callback()</span></code> 将在 <code class="docutils literal notranslate"><span class="pre">mytemplate.html</span></code> 被渲染后被调用，并将提供完全渲染的 <a class="reference internal" href="#django.template.response.TemplateResponse" title="django.template.response.TemplateResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemplateResponse</span></code></a> 实例作为参数。</p>
<p>如果模板已经被渲染，回调将被立即调用。</p>
</div>
</div>
<div class="section" id="s-using-templateresponse-and-simpletemplateresponse">
<span id="using-templateresponse-and-simpletemplateresponse"></span><h2>使用 <code class="docutils literal notranslate"><span class="pre">TemplateResponse</span></code> 和 <code class="docutils literal notranslate"><span class="pre">SimpleTemplateResponse</span></code><a class="headerlink" href="#using-templateresponse-and-simpletemplateresponse" title="永久链接至标题">¶</a></h2>
<p>一个 <a class="reference internal" href="#django.template.response.TemplateResponse" title="django.template.response.TemplateResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemplateResponse</span></code></a> 对象可以被用于任何可以使用普通 <a class="reference internal" href="request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.http.HttpResponse</span></code></a> 的地方。它也可以作为调用 <a class="reference internal" href="../topics/http/shortcuts.html#django.shortcuts.render" title="django.shortcuts.render"><code class="xref py py-func docutils literal notranslate"><span class="pre">render()</span></code></a> 的替代。</p>
<p>例如，下面的视图返回一个 <a class="reference internal" href="#django.template.response.TemplateResponse" title="django.template.response.TemplateResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemplateResponse</span></code></a>，其中有一个模板和一个包含查询集的上下文：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.template.response</span> <span class="kn">import</span> <span class="n">TemplateResponse</span>

<span class="k">def</span> <span class="nf">blog_index</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">TemplateResponse</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;entry_list.html&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;entries&#39;</span><span class="p">:</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()})</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#"><code class="docutils literal notranslate"><span class="pre">TemplateResponse</span></code> 和 <code class="docutils literal notranslate"><span class="pre">SimpleTemplateResponse</span></code></a><ul>
<li><a class="reference internal" href="#simpletemplateresponse-objects"><code class="docutils literal notranslate"><span class="pre">SimpleTemplateResponse</span></code> 对象</a><ul>
<li><a class="reference internal" href="#attributes">属性</a></li>
<li><a class="reference internal" href="#methods">方法</a></li>
</ul>
</li>
<li><a class="reference internal" href="#templateresponse-objects"><code class="docutils literal notranslate"><span class="pre">TemplateResponse</span></code> 对象</a><ul>
<li><a class="reference internal" href="#id1">方法</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-rendering-process">渲染过程</a><ul>
<li><a class="reference internal" href="#post-render-callbacks">渲染后回调</a></li>
</ul>
</li>
<li><a class="reference internal" href="#using-templateresponse-and-simpletemplateresponse">使用 <code class="docutils literal notranslate"><span class="pre">TemplateResponse</span></code> 和 <code class="docutils literal notranslate"><span class="pre">SimpleTemplateResponse</span></code></a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="templates/api.html"
                        title="上一章">Django 模板语言：对于 Python 开发者</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="unicode.html"
                        title="下一章">Unicode 数据</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/ref/template-response.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="templates/api.html" title="Django 模板语言：对于 Python 开发者">previous</a>
     |
    <a href="index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="unicode.html" title="Unicode 数据">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>